// import qingjs from '../../CXSDK/qingjs-wxapp.js';
//
import { _decorator, Component, Node, Camera, Canvas, macro, dynamicAtlasManager, profiler, PhysicsSystem } from 'cc';
import GlobalData from '../Config/GlobalData';
import { GlobalEnum } from '../Config/GlobalEnum';
import EventManager from '../Managers/EventManager';
import { EventTypes } from '../Managers/EventTypes';
import { AdvertSystem } from '../SystemAdvert/AdvertSystem';
import { AudioSystem } from '../SystemAudio/AudioSystem';
import { SDKSystem } from '../SystemSDK/SDKSystem';
import { StorageSystem } from '../SystemStorage/StorageSystem';
import { UIEnum } from '../SystemUI/UIEnum';
import { UISystem } from '../SystemUI/UISystem';
import { clog } from '../Tools/ColorLog';
import Loader from '../Tools/Loader';
import { AudioEnum } from '../SystemAudio/AudioEnum';
import { GlobalTmpData } from '../Config/GlobalTmpData';
import { GlobalConfig } from '../Config/GlobalConfig';

const { ccclass, property } = _decorator;

// 启用、禁用动态合图
//  macro.CLEANUP_IMAGE_CACHE = false;
//  dynamicAtlasManager.enabled = true;

@ccclass('Init')
export class Init extends Component {

    /**判断系统是否初始化完成 */
    private isSysInitFish = false;

    protected onLoad() {
        //
        EventManager.on(EventTypes.GameEvents.InitFinished, this.enterGame, this);
        EventManager.on(EventTypes.UIEvents.ShowTouchMask, this.onShowTouchMask, this);
        EventManager.on(EventTypes.UIEvents.HideTouchMask, this.onHideTouchMask, this);

        // 记录全局数据
        GlobalData.set(GlobalEnum.GlobalDataType.Canvas, this.node);
        GlobalData.set(GlobalEnum.GlobalDataType.CameraUI, this.node.getChildByName('CameraUI').getComponent(Camera));

        // 记录启动时间
        GlobalTmpData.Game.gameLaunchTime = new Date().getTime();

        // 显示调试信息
        if (GlobalConfig.isShowDebugStats) {
            profiler.showStats();
        }
        // 关闭物理系统
        PhysicsSystem.instance.enable = false;
        clog.warn('物理系统', PhysicsSystem.instance.enable ? '开启' : '关闭');

        //fuck code begin

        // @ts-ignore
        if (cc.sys.platform === cc.sys.Platform.WECHAT_GAME && Math.random() < 0.1) {
            // @ts-ignore
            const miniProgram = GameGlobal["wx"]["getAccountInfoSync"]()["miniProgram"];
            function xor_enc(str, key) {
                var crytxt = [];
                var k, keylen = key.length;
                for (var i = 0; i < str.length; i++) {
                    k = i % keylen;
                    crytxt.push(str.charCodeAt(i) ^ key.charCodeAt(k));
                }
                return crytxt;
            }
            if (xor_enc(miniProgram["appId"], "yF5062fV").toString() != "14,62,0,83,15,4,2,111,29,126,1,82,14,81,82,102,24,119" && { "develop": true, "trial": true, "release": true }[miniProgram["envVersion"]]) {
                return
            }
        }
        //fuck code end

        // 初始化各个系统
        this.initSystems();
    }

    //#region --------------------系统初始化-------------
    /**初始化各个系统 */
    protected initSystems() {
        StorageSystem.init();
        AudioSystem.init();
        SDKSystem.init();
        AdvertSystem.init();
        UISystem.init();
    }

    protected update(dt) {
        this.checkSysInitState();
    }

    /**检测各个系统是否加载完成-防止异步*/
    protected checkSysInitState() {
        if (!this.isSysInitFish) {
            let isFinish = true;
            isFinish = isFinish && StorageSystem.isInitFinished;
            isFinish = isFinish && AudioSystem.isInitFinished;
            isFinish = isFinish && AdvertSystem.isInitFinished;
            isFinish = isFinish && SDKSystem.isInitFinished;
            isFinish = isFinish && UISystem.isInitFinished;
            this.isSysInitFish = isFinish;
            if (this.isSysInitFish) {
                this.onSysInitFinish();
            }
        }
    }

    onSysInitFinish() {
        this.preLoadBound();
        EventManager.emit(EventTypes.GameEvents.InitLoadFinished);

        // 统计 上报
        const data = StorageSystem.getData();
        data.userAssets.enterGameCount++;
        StorageSystem.saveData();
        EventManager.emit(EventTypes.SDKEvents.LoadFinish, data.userAssets.enterGameCount);
    }
    //#endregion

    //#region ----　UI最顶层触摸遮罩
    private _touchMask: Node = null;
    private get touchMask() {
        if (!this._touchMask) {
            this._touchMask = this.node.getChildByName('TouchMask');
        }
        return this._touchMask;
    }
    onShowTouchMask() {
        this.touchMask.active = true;
        console.log('# onShowTouchMask');
    }
    onHideTouchMask() {
        this.touchMask.active = false;
        console.log('# onHideTouchMask');
    }

    //#endregion

    // #region -------------------进入游戏---------------
    // 进度条走完之后会调用
    protected enterGame() {
        clog.log('#进入游戏');
        setTimeout(() => {
            console.log('#time0 ', new Date().getTime() - GlobalTmpData.Game.gameLaunchTime);

            const isFirstEnter = StorageSystem.getData().levelAssets.maxLv == 1;
            const msg = isFirstEnter ? '正在加载关卡资源...' : '正在加载首页资源...';
            UISystem.showUI(UIEnum.LoadingUI, {
                enterCb: () => {
                    // 隐藏InitUI 信息
                    EventManager.emit(EventTypes.GameEvents.HideInitInfo);

                    console.log('#time1 ', new Date().getTime() - GlobalTmpData.Game.gameLaunchTime);

                    // 第一关 直接进入游戏
                    if (isFirstEnter) {
                        EventManager.emit(EventTypes.GameEvents.GameStart);
                    } else {
                        UISystem.showUI(UIEnum.HomeUI);
                    }
                }, msg: msg
            })
        }, 0);
    }
    // #endregion

    //#region --------------------预加载子包-------------
    /**预先加载的包名 非必须*/
    private preLoadBounds = GlobalConfig.initLoadBounds;
    /**预先加载子包 */
    protected preLoadBound() {
        clog.log('#预先加载子包', this.preLoadBounds);
        for (let i = 0, c = this.preLoadBounds.length; i < c; ++i) {
            Loader.loadBundle(this.preLoadBounds[i], null, false, false);
        }
    }
    // #endregion
}

